import { Injectable } from '@angular/core';
declare var Wechat: any;

@Injectable({
    providedIn: 'root'
})

export class WechatService {

    constructor() {

    }

    public generateRandomString({ randomFlag = false, min, max }: any) {
        let str = '';
        let range = min;
        const arr = [
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
            'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y', 'Z'
        ];

        if (randomFlag) {
            range = Math.round(Math.random() * (max - min)) + min;
        }
        for (let i = 0; i < range; i++) {
            const pos = Math.round(Math.random() * (arr.length - 1));
            str += arr[pos];
        }
        return str;
    }

    public generatePreSignString(singData) {
        const keys = Object.keys(singData);
        const sortKeys = keys.sort();
        const newArgs = {};
        sortKeys.forEach(key => {
            newArgs[key.toLowerCase()] = singData[key];
        });

        let resultString = '';
        Object.entries(newArgs).forEach(([ key, val ]) => {
            resultString += `&${key}=${val}`;
        });
        resultString = resultString.substr(1);

        return resultString;
    }

    public wechatIsInstall() {
        return new Promise<boolean>((resolve, reject) => {
            Wechat.isInstalled(installed => resolve(installed), reason => reject(reason));
        });
    }

    public wechatAuthLogin(): any {
        return new Promise((resolve, reject) => {
            const scope = 'snsapi_userinfo';
            const state = `_${+new Date()}`;
            Wechat.auth(scope, state, (response) => resolve(response), reason => reject(reason));
        });
    }

    public wechatPaymentRequest(params): any {
        return new Promise((resolve, reject) => {
            Wechat.sendPaymentRequest(params, result => resolve(result), error => reject(error));
        });
    }
}
